/*******************************************************************************
 * Copyright (c) 2002 Boris Pruessmann and others. All rights reserved. This
 * program and the accompanying materials are made available under the terms of
 * the Common Public License v0.5 which accompanies this distribution, and is
 * available at http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors: Boris Pruessmann - Initial implementation.
 ******************************************************************************/
package net.sourceforge.perforce.ui.action;

import com.google.common.collect.Sets;

import net.sourceforge.perforce.core.PerforceCorePlugin;
import net.sourceforge.perforce.core.PerforceException;
import net.sourceforge.perforce.core.api.IPerforceServer;
import net.sourceforge.perforce.core.resources.IP4File;

import org.eclipse.jface.action.IAction;

import java.util.Set;

/**
 * @version $Revision: 488 $
 * @author <a href="mailto:bpruessmann@users.sourceforge.net">Boris
 *         Pruessmann</a>
 */
public class ScheduleForResolveAction extends P4FileAction {
  //----------------------------------------------------------------------------
  // -- Public Methods

  @Override
  public void run(IAction action) {
    IP4File[] files = getSelectedPerforceFiles();

    Set<IPerforceServer> serverSet = Sets.newHashSet();
    try {
      for (int i = 0; i < files.length; i++) {
        IP4File file = files[i];

        IPerforceServer server = file.getServer();
        server.sync(file.getLocation().toOSString(), "#head", null);
        serverSet.add(server);
      }
    } catch (PerforceException e) {
      handle(e);
    } finally {
      if (!serverSet.isEmpty()) {
        IPerforceServer[] servers = serverSet.toArray(new IPerforceServer[serverSet.size()]);
        PerforceCorePlugin.getPlugin().broadcastChangelistStateChanges(servers);
      }
    }
  }

  // ---------------------------------------------------------------------------
  // Protected Methods

  @Override
  protected boolean isEnabled() {
    IP4File[] files = getSelectedPerforceFiles();
    for (int i = 0; i < files.length; i++) {
      IP4File file = files[i];

      if (!file.getClientName().equals(file.getServer().getClient()) || file.needsResolve()) {
        return false;
      }
    }
    return true;
  }
}
